﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Core
{
    /// <summary>
    /// Pre condition
    /// </summary>
    public class PreCondition
    {
        /// <summary>
        /// Expressions list
        /// </summary>
        private List<LogicalExpression> _Expressions = new List<LogicalExpression>();

        /// <summary>
        /// Logical connectives list
        /// </summary>
        private List<LogicalConnective> _LogicalConnectives = new List<LogicalConnective>();
        

        /// <summary>
        /// Constructor
        /// </summary>
        public PreCondition(String input)
        {
            // sample: pre A>=0 and B>0

            // pre                         : pre keyword
            // (?<expression>\S+)*         : first expression (if any)
            // (?<whitespace>\s+)(?<connective>(and|or))\s+(?<expression>\S+))* 
            //                             : other expressions (if any)
            String pattern = @"pre 
                              ((?<whitespace>\s+)(?<expression>\S+)*
                              ((?<whitespace>\s+)(?<connective>(and|or))(?<whitespace>\s+)(?<expression>\S+))*)";

            // is match ?
            if (Regex.IsMatch(input, pattern, RegexOptions.IgnorePatternWhitespace))
            {
                Match match = Regex.Match(input, pattern, RegexOptions.IgnorePatternWhitespace);

                // add logical expressions to list
                foreach (Capture capture in match.Groups["expression"].Captures)
                {
                    _Expressions.Add(new LogicalExpression(capture.Value));
                }

                // add logical connectives to list
                foreach (Capture capture in match.Groups["connective"].Captures)
                {
                    _LogicalConnectives.Add(LogicalConnectiveFactory.Create(capture.Value));
                }
            }
            else
            {
                throw new Exception("Pre condition ERROR!");
            }
        }

        /// <summary>
        /// Override ToString method
        /// </summary>
        /// <returns></returns>
        public override String ToString()
        {
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < _Expressions.Count; ++i )
            {
                builder.AppendFormat("{0}", _Expressions[i].ToString());
                if(i < _Expressions.Count - 1)
                {
                    builder.AppendFormat(" {0} ", _LogicalConnectives[i].ToString());
                }
            }
            return builder.ToString();
        }
    }
}
